<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>权限树扩展分享</title>
	<link rel="stylesheet" type="text/css" href="../../lib/layui/css/layui.css">
</head>
<body>
<div class="layui-container">
	<div class="layui-row">
		<div class="layui-col-md6 layui-col-md-offset1">
			<fieldset class="layui-elem-field layui-field-title"><legend>权限树扩展分享</legend></fieldset>
			<!-- 此扩展能递归渲染一个权限树，点击深层次节点，父级节点中没有被选中的节点会被自动选中，单独点击父节点，子节点会全部 选中/去选中 -->
			<form class="layui-form">
				<div class="layui-form-item">
					<label class="layui-form-label">角色名称</label>
					<div class="layui-input-block">
						<input class="layui-input" type="text" name="name" placeholder="请输入角色名称" />
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">选择权限</label>
					<div class="layui-input-block">
						<div id="LAY-auth-tree-index"></div>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn" type="submit" lay-submit lay-filter="LAY-auth-tree-submit">提交</button>
						<button class="layui-btn layui-btn-primary" type="reset">重置</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>
</body>
<script type="text/javascript" src="../../lib/layui/layui.js"></script>
<script type="text/javascript">
layui.config({
	base: '../../module/',
}).extend({
	authtree: 'authtree',
});
layui.use(['jquery', 'authtree', 'form', 'layer'], function(){
	var $ = layui.jquery;
	var authtree = layui.authtree;
	var form = layui.form;
	var layer = layui.layer;
	// 初始化
	$.ajax({
		url: '../../data/authtree.json',
		dataType: 'json',
		success: function(data){
			// 渲染时传入渲染目标ID，树形结构数据（具体结构看样例，checked表示默认选中），以及input表单的名字
			authtree.render('#LAY-auth-tree-index', data.data.trees, {inputname: 'authids[]', layfilter: 'lay-check-auth', openall: false});

			// 监听自定义lay-filter选中状态，PS:layui现在不支持多次监听，所以扩展里边只能改变触发逻辑，然后引起了事件冒泡延迟的BUG，要是谁有好的建议可以反馈我
			form.on('checkbox(lay-check-auth)', function(data){
				// 获取所有节点
				var all = authtree.getAll('#LAY-auth-tree-index');
				console.log('all', all);
				// 获取所有已选中节点
				var checked = authtree.getChecked('#LAY-auth-tree-index');
				console.log('checked', checked);
				// 获取所有未选中节点
				var notchecked = authtree.getNotChecked('#LAY-auth-tree-index');
				console.log('notchecked', notchecked);
				// 注意这里：需要等待事件冒泡完成，不然获取叶子节点不准确。
				setTimeout(function(){
					// 获取选中的叶子节点
					var leaf = authtree.getLeaf('#LAY-auth-tree-index');
					console.log('leaf', leaf);
				}, 100);
			});
		}
	});
	form.on('submit(LAY-auth-tree-submit)', function(obj){
		var authids = authtree.getAll('#LAY-auth-tree-index');
		console.log('Choosed authids is', authids);
		obj.field.authids = authids;
		$.ajax({
			url: 'tree.json',
			dataType: 'json',
			data: obj.field,
			success: function(res){
				layer.alert('提交成功！');
			}
		});
		return false;
	});
});
</script>
</html>